package io.renren.modules.live.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.RRException;
import io.renren.common.utils.FastDFSClientUtils;
import io.renren.common.utils.PageResult;
import io.renren.config.LiveConfig;
import io.renren.modules.live.constants.ResourcesConstants;
import io.renren.modules.live.dao.FanweAnchorDao;
import io.renren.modules.live.entity.FanweAnchorEntity;
import io.renren.modules.live.entity.ResourceBean;
import io.renren.modules.live.service.FanweAnchorService;
import io.renren.modules.live.vo.AnchorUpdateVideoVo;
import io.renren.modules.live.vo.FanweVideoEntityVo;
import io.renren.modules.live.vo.FindByVoideListVideoNameAndAnchorNameVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.live.entity.FanweVideoEntity;
import io.renren.modules.live.service.FanweVideoService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 直播表
 *
 * @author shaoqi
 * @email sunlightcs@gmail.com
 * @date 2020-11-17 09:18:22
 */
@Api(tags = "直播间信息接口")
@RestController
@RequestMapping("video")
@Log4j2
public class FanweVideoController {
    @Autowired
    private FanweVideoService fanweVideoService;

    @Autowired
    private FanweAnchorService fanweAnchorService;
    @Autowired
    private FanweVideoService videoService;


    @PostMapping("/left/anchorStartLive")
    @ApiOperation(value = "主播开始直播（设置直播间，返回推流地址）")
    public R getUserAttentionAnchor(
                                    @RequestParam("muFile") @ApiParam("封面") MultipartFile muFile,
                                    @RequestBody @ApiParam(value = "主播设置的直播间信息") FanweVideoEntityVo fanweVideoEntityVo) {
        ResourceBean fileUrlAndName = uploadFileUitl(muFile);
        FanweVideoEntity videoEntity1 = videoService.getByAnchorId(fanweVideoEntityVo.getAnchorId());
        videoEntity1.setBeginTime(new Date(System.currentTimeMillis()));
        videoEntity1.setLiveIn(1);
        videoEntity1.setLiveImage(fileUrlAndName.getFileUrl());
        videoEntity1.setAnchorId(fanweVideoEntityVo.getAnchorId());
        videoEntity1.setAnchorName(fanweVideoEntityVo.getAnchorName());
        videoEntity1.setCity(fanweVideoEntityVo.getCity());
        videoEntity1.setProvince(fanweVideoEntityVo.getProvince());
        videoEntity1.setSex(fanweVideoEntityVo.getSex());
        videoEntity1.setIsLivePay(fanweVideoEntityVo.getIsLivePay());
        videoEntity1.setLiveFee(fanweVideoEntityVo.getLiveFee());
        videoEntity1.setLivePayType(fanweVideoEntityVo.getLivePayType());
        videoEntity1.setRoomTitle(fanweVideoEntityVo.getRoomTitle());
        videoEntity1.setPayRoomId(fanweVideoEntityVo.getPayRoomId());
        videoService.updateById(videoEntity1);
        //返回直播间推流地址
        return R.ok().put("rmtpPushUrl", videoEntity1.getPushRtmp());
    }
    private ResourceBean uploadFileUitl(MultipartFile file){
        String extName = "";
        String fileName = "";
        String originalFilename = file.getOriginalFilename();
        if(originalFilename.contains(".")) {
            //拆分文件路径
            String[] fileArray = originalFilename.split("\\.");
            //获取文件扩展名
            extName = fileArray[1];
            //获取文件名
            fileName = fileArray[0];
        }else {
            fileName = originalFilename;
        }
        byte[] bytes = null;
        try {
            bytes = file.getBytes(); //将文件转换成字节流形式
        } catch (IOException e) {
            log.info(e);
        }
        //调用上传文件的具体方法
        String fileId= FastDFSClientUtils.upload(bytes,extName);
        return new ResourceBean(ResourcesConstants.getResourcesUrl(fileId), fileName);
    }


    @GetMapping("/left/getRmtpPushUrl")
    @ApiOperation(value = "根据直播间id获取直播间推流地址接口")
    public R getRmtpPushUrl(@ApiParam(value = "直播间ID",required = true)Integer liveId) {
        FanweVideoEntity videoEntity = videoService.getById(liveId);
        if (videoEntity == null) {
            return R.error("当前直播间不存在!!");
        }
        //返回直播间推流地址
        return R.ok().put("rmtpPushUrl", videoEntity.getPushRtmp());
    }


    @ApiOperation("获取全部直播中的直播间")
    @GetMapping("/left/getVoideList")
    //@RequiresPermissions("live:fanwevideo:list")
    public R getVoideList( @ApiParam("当前页") Long page,
                           @ApiParam("每页显示数量")Long size){
        Page<FanweVideoEntity> userPage = new Page<>(page, size);
        QueryWrapper<FanweVideoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("live_in",1);
        fanweVideoService.page(userPage, wrapper);
        PageResult<FanweVideoEntity> result1 = new PageResult<>();
        result1.setTotal(userPage.getTotal());
        result1.setRows(userPage.getRecords());
        return R.ok("获取成功").put("pageResult",result1);
    }

    @ApiOperation("获取推荐的直播中的直播间")
    @GetMapping("/left/getVoideRecommendList")
    //@RequiresPermissions("live:fanwevideo:list")
    public R getVoideRecommendList( @ApiParam("当前页") Long page,
                                    @ApiParam("每页显示数量")Long size){
        Page<FanweVideoEntity> userPage = new Page<>(page, size);
        QueryWrapper<FanweVideoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("recommend",1);
        fanweVideoService.page(userPage, wrapper);
        PageResult<FanweVideoEntity> result1 = new PageResult<>();
        result1.setTotal(userPage.getTotal());
        result1.setRows(userPage.getRecords());
        return R.ok("获取成功").put("pageResult",result1);
    }

    @ApiOperation("获取最新直播中的直播间")
    @GetMapping("/left/getNewVoideList")
    //@RequiresPermissions("live:fanwevideo:list")
    public R getNewVoideList(){
        List<FanweVideoEntity> videoList= fanweVideoService.getVoideList();
        List<FanweVideoEntity> videoEntityList = videoList.stream().sorted(Comparator.comparing(FanweVideoEntity::getBeginTime).reversed()).collect(Collectors.toList());
        if(videoEntityList.isEmpty()&&videoEntityList.size()==0){
            return R.error("没有最新直播的直播间");
        }
        return R.ok("获取成功").put("videoList",videoEntityList);
    }

    @ApiOperation("获取开启收费直播中的直播间信息")
    @GetMapping("/left/getChargesVoideList")
    //@RequiresPermissions("live:fanwevideo:list")
    public R getChargesVoideList(@ApiParam("当前页") Long page,
                                  @ApiParam("每页显示数量")Long size){
            Page<FanweVideoEntity> userPage = new Page<>(page, size);
            QueryWrapper<FanweVideoEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("is_live_pay",1);
            fanweVideoService.page(userPage, wrapper);
            PageResult<FanweVideoEntity> result1 = new PageResult<>();
            result1.setTotal(userPage.getTotal());
            result1.setRows(userPage.getRecords());
            return R.ok("获取成功").put("pageResult",result1);
    }

    @ApiOperation("根据主播昵称或直播间标题模糊查询直播中的直播间集合")
    @PostMapping("/left/findByVoideListVideoNameAndAnchorName")
    //@RequiresPermissions("live:fanwevideo:list")
    public R findByVoideListVideoNameAndAnchorName(@ApiParam(value = "模糊查询参数",required = true)@RequestParam String content){
        if(content==null){
            return R.error("内容为空,请输入要查询的内容");
        }
        List<FanweVideoEntity> videoList1 = new ArrayList<>();
        List<FanweVideoEntity> videoList2 = new ArrayList<>();
        List<FanweVideoEntity> videoList3 = new ArrayList<>();
        List<FanweVideoEntity> videoListResult = new ArrayList<>();
        //模糊查询到直播中的直播间
        videoList1 = fanweVideoService.findByVoideListVideoNameAndAnchorName(content);
        if(!videoList1.isEmpty()&&videoList1.size()!=0){
            videoListResult = Stream.of(videoList1, videoList2)
                    .flatMap(Collection::stream)
                    .distinct()
                    .collect(Collectors.toList());
        }
        //模糊查询到主播的昵称ID集合
        List<Long> anchorIdList = fanweAnchorService.findByVoideListVideoNameAndAnchorName(content);
        if(!anchorIdList.isEmpty()&&anchorIdList.size()!=0){
            //根据主播ID集合查询直播间
            videoList1 = fanweVideoService.findByAnchorIdList(anchorIdList);
            if(!videoList1.isEmpty()&&videoList1.size()!=0){
                //合并两个集合并去重复返回
                videoList3 = Stream.of(videoList1, videoList2)
                        .flatMap(Collection::stream)
                        .distinct()
                        .collect(Collectors.toList());
            }
        }
        List<FanweVideoEntity> list = Stream.of(videoList3, videoListResult)
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());
        if(!list.isEmpty()&&list.size()!=0){
            return R.ok("获取成功").put("videoList",list);
        }
        return R.error("找不到您要找的直播间");
    }

    @ApiOperation("获取颜值高到低的主播直播间集合信息(直播中)")
    @GetMapping("/left/getHightoLowVoideList")
    //@RequiresPermissions("live:fanwevideo:list")
    public R getHightoLowVoideList( @ApiParam("当前页") Long page,
                                    @ApiParam("每页显示数量")Long size){
//        //查询正在直播的直播间信息
//        List<FanweVideoEntity> videoList= fanweVideoService.getVoideList();
//        //取出主播的ID
//        List<Integer> anchorIdList = videoList.stream().map(FanweVideoEntity::getAnchorId).collect(Collectors.toList());
//        //根据主播ID集合查询查询主播粉丝数(从多到少排序)
//        List<Integer> sortedFansAnchorIdList = fanweAnchorService.selectAnchorFans(anchorIdList);
        //查询数据
        List<FanweVideoEntity> videoListResult = fanweVideoService.getBysortedFansAnchorIdListId(page,size);
//        videoList.stream().filter(video -> video.getAnchorId())
//        List<FanweVideoEntity> videoList= fanweVideoService.getVoideList();
//        List<FanweVideoEntity> videoEntityList = videoList.stream().sorted(Comparator.comparing(FanweVideoEntity::getBeginTime).reversed()).collect(Collectors.toList());
//        System.out.println("元素的属性值倒序：" + videoEntityList);
        return R.ok("获取成功").put("videoList",videoListResult);
    }

    @GetMapping("/left/getVoideById")
    @ApiOperation("根据直播间ID获取直播间信息")
    public R info(@ApiParam(value = "直播间ID",required = true)Integer id){
		FanweVideoEntity fanweVideo = fanweVideoService.getById(id);
        return R.ok("获取成功").put("fanweVideo", fanweVideo);
    }




    @PostMapping("/save")
    @ApiOperation("管理员添加直播间")
    //@RequiresPermissions("live:fanwevideo:save")
    public R save(@RequestBody FanweVideoEntity fanweVideo){
		fanweVideoService.save(fanweVideo);
        return R.ok("添加成功");
    }

    @PutMapping("/left/anchorUpdateVideo")
    @ApiOperation("主播修改直播间信息")
    //@RequiresPermissions("live:fanwevideo:update")
    public R anchorUpdateVideo(
                    @RequestBody AnchorUpdateVideoVo updateVideoVo){
        //设置收费直播间ID
        updateVideoVo.setPayRoomId(updateVideoVo.getVideoId());
        fanweVideoService.anchorUpdateVideo(updateVideoVo);
        return R.ok("修改成功");
    }


    @PutMapping("/update")
    //@RequiresPermissions("live:fanwevideo:update")
    @ApiOperation("管理员修改直播间信息")
    public R update(@RequestBody FanweVideoEntity fanweVideo){
        fanweVideoService.updateById(fanweVideo);
        return R.ok("修改成功");
    }


    @DeleteMapping("/delete")
    //@RequiresPermissions("live:fanwevideo:delete")
    @ApiOperation("管理员删除直播间")
    public R delete(@RequestBody Integer[] ids){
		fanweVideoService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
